<template>
  <div class="yd-tabs">
    <div class="tabs-header">
      <div class="active-border" :style="{width:`${width}px`,transform: `translateX(${offSet}px)`}"></div>
      <div
        class="item-title"
        :class="[activeName==item.props.name?'active-name':'']"
        v-for="item in panes"
        :key="item.props.name"
        :data-name="item.props.name"
        @click="handleClickActive(item.props.name)"
        :ref="setItemRef"
      >{{item.props.label}}</div>
    </div>
    <div class="tabs-container">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import { getCurrentInstance, reactive, toRefs, onMounted } from "vue";
export default {
  name: "yd-tabs",
  props: {
    modelValue: {
      type: [String, Number],
      default: ""
    }
  },
  setup(props, ctx) {
    const instance = getCurrentInstance();
    const state = reactive({
      panes: instance.slots.default() || [],
      activeName: props.modelValue,
      itemRefs: [],
      width: 0,
      offSet: 0
    });
    const handleClickActive = name => {
      state.activeName = name;
      for (let i = 0; i < state.itemRefs.length; i++) {
        if (name == state.itemRefs[i].dataset.name) {
          state.width = state.itemRefs[i].clientWidth;
          state.offSet = state.itemRefs[i].offsetLeft;
          break;
        }
      }
      ctx.emit("update:modelValue", name);
    };
    //获取dom节点生成refs
    const setItemRef = e => {
      state.itemRefs.push(e);
    };
    onMounted(() => {
      for (let i = 0; i < state.itemRefs.length; i++) {
        if (props.modelValue == state.itemRefs[i].dataset.name) {
          state.width = state.itemRefs[i].clientWidth;
          state.offSet = state.itemRefs[i].offsetLeft;
          break;
        }
      }
    });

    return {
      ...toRefs(state),
      handleClickActive,
      setItemRef
    };
  }
};
</script>

<style lang="scss" scoped>
.yd-tabs {
  .tabs-header {
    position: relative;
    display: flex;
    align-items: center;
    padding: 10px 0;
    margin-bottom: 20px;
    .active-border {
      position: absolute;
      bottom: 0;
      left: 0;
      height: 2px;
      background-color: #409eff;
      z-index: 2;
      transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      list-style: none;
    }
    .item-title {
      margin: 0 14px;
      font-size: 14px;
      cursor: pointer;
      &:nth-child(2) {
        margin-left: 0;
      }
      &:last-child {
        margin-right: 0;
      }
      &:hover {
        color: #409eff;
      }
    }
    .active-name {
      color: #409eff;
    }
    &:after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 2px;
      background-color: #e4e7ed;
      z-index: 1;
    }
  }
}
</style>